package io.jee.runshan.controller.admin;

import io.jee.medusa.vo.QiyeMember;
import io.jee.runshan.domain.remote.qiye.DepartmentCreate;
import io.jee.runshan.domain.remote.qiye.DepartmentList;
import io.jee.runshan.domain.remote.qiye.UserDetail;
import io.jee.runshan.domain.remote.qiye.UserInvite;
import io.jee.runshan.domain.remote.qiye.UserList;
import io.jee.runshan.domain.remote.qiye.base.Response;
import io.jee.runshan.domain.remote.qiye.request.DepartmentData;
import io.jee.runshan.domain.remote.qiye.request.UserBatchdeleteData;
import io.jee.runshan.domain.remote.qiye.request.UserCreateData;
import io.jee.runshan.domain.remote.qiye.request.UserInviteData;
import io.jee.runshan.domain.remote.qiye.response.DepartmentListData;
import io.jee.runshan.domain.remote.qiye.response.UserListData;
import io.jee.runshan.service.remote.qiye.IDeptService;
import io.jee.runshan.service.remote.qiye.IUserService;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/admin/qiye/dept")
public class QiyeDeptController {
	@Resource
	private IDeptService deptService;
	
	@Resource
	private IUserService userService;
	
	private static final String BOOK = "admin/qiye/dept/book";
	
	@RequestMapping("/book")
	public ModelAndView book(){
		return new ModelAndView(BOOK);
	}
	
	@RequestMapping(value = "/ajaxDepts", produces = { "application/json" })
	@ResponseBody
	public DepartmentList ajaxDepts() {
		DepartmentList response = null;
		try {
			response = deptService.list();
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	@RequestMapping(value = "/ajaxDeptMembers", produces = { "application/json" })
	@ResponseBody
	public List<QiyeMember> ajaxDeptMembers() {
		List<QiyeMember> deptMembers = null;
		try {
			DepartmentList response = deptService.list();
			if (response == null || response.getDepartment() == null || response.getDepartment().isEmpty()) {
				return null;
			}
			deptMembers = new ArrayList<QiyeMember>();
			UserList userList = userService.list(1, 1, 0);
			for (DepartmentListData department : response.getDepartment()) {
				QiyeMember dept = new QiyeMember();
				BeanUtils.copyProperties(department, dept);
				deptMembers.add(dept);
			}
			
			for (UserListData user : userList.getUserlist()) {
				for (Integer deptId : user.getDepartment()) {
					QiyeMember member = new QiyeMember();
					member.setIconSkin("memberIcon");
					member.setName(user.getPosition() + " - " + user.getName());
					member.setValue(user.getName());
					member.setParentid(deptId);
					member.setUserid(user.getUserid());
					deptMembers.add(member);
				}
			}
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return deptMembers;
	}
	
	@RequestMapping(value = "/ajaxCreate", produces = { "application/json" })
	@ResponseBody
	public DepartmentCreate ajaxCreate(DepartmentData data) {
		DepartmentCreate response = null;
		try {
			response = deptService.create(data);
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	@RequestMapping(value = "/ajaxUpdate", produces = { "application/json" })
	@ResponseBody
	public Response ajaxUpdate(DepartmentData data) {
		Response response = null;
		try {
			response = deptService.update(data);
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	@RequestMapping(value = "/ajaxDelete", produces = { "application/json" })
	@ResponseBody
	public Response ajaxDelete(Integer id) {
		Response response = null;
		try {
			response = deptService.delete(id);
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	@RequestMapping(value = "/ajaxUserList", produces = { "application/json" })
	@ResponseBody
	public UserList ajaxUserList(Integer deptId,Integer fetchChild,Integer status) {
		UserList response = null;
		try {
			response = userService.list(deptId, fetchChild, status);
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	@RequestMapping(value = "/ajaxUserCreate", produces = { "application/json" })
	@ResponseBody
	public Response ajaxUserCreate(UserCreateData data) {
		Response response = null;
		try {
			response = userService.create(data);
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	@RequestMapping(value = "/ajaxUserDetail", produces = { "application/json" })
	@ResponseBody
	public UserDetail ajaxUserDetail(String userid) {
		UserDetail response = null;
		try {
			response = userService.detail(userid);
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	@RequestMapping(value = "/ajaxUserUpdate", produces = { "application/json" })
	@ResponseBody
	public Response ajaxUserUpdate(UserCreateData data) {
		Response response = null;
		try {
			response = userService.update(data);
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	@RequestMapping(value = "/ajaxUserDelete", produces = { "application/json" })
	@ResponseBody
	public Response ajaxUserDelete(String id) {
		Response response = null;
		try {
			response = userService.delete(id);
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	@RequestMapping(value = "/ajaxUserBatchDelete", produces = { "application/json" })
	@ResponseBody
	public Response ajaxUserBatchDelete(UserBatchdeleteData ids) {
		Response response = null;
		try {
			response = userService.batchdelete(ids);
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	@RequestMapping(value = "/ajaxUserInvite", produces = { "application/json" })
	@ResponseBody
	public UserInvite ajaxUserInvite(UserInviteData data) {
		UserInvite response = null;
		try {
			response = userService.invite(data);
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	@RequestMapping(value = "/ajaxUserEnable", produces = { "application/json" })
	@ResponseBody
	public Response ajaxUserEnable(String userid, Integer enable) {
		Response response = null;
		try {
			UserDetail detail = userService.detail(userid);
			UserCreateData data = new UserCreateData();
			BeanUtils.copyProperties(detail, data);
			data.setEnable(enable);
			response = userService.update(data);
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * 批量导入
	 * @throws IOException 
	 * @throws IllegalStateException 
	 * 
	 */
	@RequestMapping(value = "/import" ,produces = {"application/json"})
	@ResponseBody
	public Map<Object,Object> importXls(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<Object,Object> map = new HashMap<Object,Object>();
		try {
			String tempPath = System.getProperty("java.io.tmpdir")+"/"+System.currentTimeMillis()+"/";
			
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartRequest.getFile("file");
			
			File file = new File(tempPath , multipartFile.getOriginalFilename());
			file.mkdirs();
			multipartFile.transferTo(file);
			
			map = userService.importUser(file.getPath());
	        
		} catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("msg","未知错误:" + e.getMessage());
        }
		return map;
	}
	
	/**
	 * 下载文件模板
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/download")
	public void download(HttpServletRequest request, HttpServletResponse response) {
        try {
        	String path = request.getSession().getServletContext().getRealPath("/template/import_user_sample.xls");
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
           // String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
